<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/键盘事件.css">
</head>

<body>
    <div class="box">
        <div class="menu"></div>
    </div>
    <script>
        var box = document.querySelector(".box");
        var menu = document.querySelector(".menu");
        menuStyle = getComputedStyle(menu, null);
        boxStyle = getComputedStyle(box, null);
        box.oncontextmenu = function (e) {
            if (e.target != this) return false;
            var left = e.offsetX;
            var top = e.offsetY;
            menu.style.left = (left + parseInt(menuStyle.width)) > parseInt(boxStyle.width) ? (left - parseInt(menuStyle.width) + "px") : left + "px";
            menu.style.top = (top + parseInt(menuStyle.height)) > parseInt(boxStyle.height) ? (top - parseInt(menuStyle.height) + "px") : top + "px";
            return false;
        }
        document.onkeydown = function (e) {
            switch (e.keyCode) {
                case 87:
                    console.log("w");
                    break;
                case 83:
                    console.log("s");
                    break;
                case 65:
                    console.log("a");
                    break;
                case 68:
                    console.log("d");
                    break;
            }
        }
    </script>
</body>

</html>